$(document).ready(function (){
	require(['jtopo',
		'Json2xml',
		'topoCustomNode',
		'topoCustomLink',
		'topoCustomTextNode',
		'topoCustomContainer',
		'topoCustomNephogramPublic',
		index_web_app_name + 'js/plugin/topo/group.js',
		index_web_app_name + 'js/plugin/topo/node-ui-function.js',
		index_web_app_name + 'js/plugin/topo/topo.js',
		index_web_app_name + 'js/plugin/topo/topo_show_util.js',
		'css!'+ index_web_app_name +'css/topo.css'] ,function (
			jtopo,
			Json2xml,
			CustomNode,
			CustomLink,
			CustomTextNode,
			CustomContainer,
			customNephogramPublic,
			group,
			nodeFunction,
			topo,
			topo_show_util,
			topocss){
var url = {
	importUrl : 'topoManage/getTopoMonitor'
};
var this_params = index_query_param_get();
var topoId = this_params.topoId;

var json2xml = new Json2xml({
	attributePrefix : ""
});
var json2xml2 = new Json2xml({
});
$("#content_div").css("padding" ,"0");
$("#pg-content").css("padding" ,"0");
$(".pg-content-div").css('padding','0');
if(!!this_params.hideBtnBar){
	$(".menu-bar").hide();
	$(".board").css('left','0px');
	$(".board").css('overflow','hidden');
	$(".board").css('top','0px');
	$(".board").css('right','0px');
	$(".board").css('bottom','0px');
	$(".drawing-board-bg").css('top','0px');
	$(".drawing-board").css('left','0px');
	$(".topo-right").css('left','0px');
	$(".topo-right").css('right','0px');
	var btn = $('<a data-type="aclick" href="javascript:void(0);" style="position:absolute;top:10px;right:10px;"><i class="icon-share-sign" title="详情" style="font-size:24px;color:black;"></i></a>');
	btn.click(function (){
		window.open(window.location.href.substring(0,window.location.href.indexOf('&hideBtnBar')));
	});
	$(".board").append(btn);
}else {
	this_params.changeTitle = true;
}
var mainCanvas = topo_show_util.createCanvasFactory($('.board'),'main_canvas');
var stage,scene;
$(mainCanvas).oneTime(1000,function() {
	this.width = $(this).parent().width();
	this.height = $(this).parent().height();
});

stage = new JTopo.Stage(mainCanvas);
scene = new JTopo.Scene();
scene.background = 'img/topo/backimg.png';
scene.backgroundRepeat = 'repeat';

$.ajax({
	url : index_web_app + index_soc_prefix + 'topoManage/getTopoInfo',
	data : {topoId:this_params.topoId,regionId:this_params.regionId},
	type : 'post',
	dataType : 'json',
	async : true,
	timeout : 6000,
	xhrFields: {
		withCredentials: true
	},
	success : function (data){
		var bgi = data.topoBackground;
		!!bgi && setBackgroundImage(bgi);
	},
	error : function (e)
	{
	}
});

function setBackgroundImage(url){
	var bgiurl = url.split(',')[0];
	if(!bgiurl){
		scene.background = 'img/topo/backimg.png';
		scene.backgroundRepeat = 'repeat';
	}else {
		var bgis = url.split(',');
		um_ajax_get({
			url : 'topoManage/getImageBase64',
			paramObj : {imgUri : bgis[0]},
			successCallBack : function (data){
				var img = new Image();
				img.src = data;
				scene.background = img;
				if(bgis.length==2){
					scene.backgroundRepeat = bgis[1];
				}else {
					scene.backgroundRepeat = undefined;
				}
			},
			failCallBack : function (){
				scene.background = 'img/topo/backimg.png';
				scene.backgroundRepeat = 'repeat';
			}
		})
	}
}

stage.add(scene);
topo_show_util.initStageAndScene(stage,scene);
topo_show_util.initParam(this_params);
topo_show_util.initView();

$(mainCanvas).oneTime(1000,function(){
	if(!!this_params.hideBtnBar){
		scene.mode = 'select';
		for(var i=0;i<scene.childs.length;i++){
			scene.childs[i].dragable = false;
		}
		scene.centerAndZoom();
	}
});

initEvent();
function initEvent(){
	$("#saveTopo").click(function (){
		saveTopo();
	});
	$("#exportImage").click(function (){
		exportImage();
	});
	//设置查询
	$("[data-id=query]").click(function(){
		nodeFunction.queryNode(scene,selectFunc);
	});
	//设置状态清除
	$("[data-id=clearState]").click(function(){
		nodeFunction.clearState(scene);
	});
}
function selectFunc(saveObj){
	var nodes = scene.getAllNodes();
	for(var i=0;i<nodes.length;i++){
		if(		nodes[i].name.indexOf(saveObj.name) != -1 || 
				(nodes[i].asset && nodes[i].asset.name.indexOf(saveObj.name) != -1) || 
				(nodes[i].asset && nodes[i].asset.ip.indexOf(saveObj.name) != -1) ){
			//
			nodes[i].selected = true;
			scene.selectedElements.push(nodes[i]);
		}
	}
}
function exportImage(){
	var c = mainCanvas.toDataURL('image/png');
	// c = c.replace('image/png','image/octet-stream');
	// 下载后的问题名
	// var filename = '拓扑导出_' + (new Date()).getTime() + '.png';
	// download
	// saveFile(c,filename);

	d = window.open('about:blank');
	d.document.write('<body>');
    d.document.write("<img src='" + c + "' alt='from canvas'/>");
    d.document.write('</body>');
}
/**
 * 在本地进行文件保存
 * @param  {String} data     要保存到本地的图片数据
 * @param  {String} filename 文件名
 */
var saveFile = function(data, filename){
    var save_link = document.createElementNS('http://www.w3.org/1999/xhtml', 'a');
    save_link.href = data;
    save_link.download = filename;
    var event = document.createEvent('MouseEvents');
    event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
    save_link.dispatchEvent(event);
};
function saveTopo(){
	
	var nodeStr='',nodeStr2='',linkStr='',linkStr2='',textStr='',containerStr='';

	var str = '<root x="'+scene.translateX+'" y="'+scene.translateY+'">';

	str += '<nodes>';
	var nodeNum = 0;
	var nodeSecDomainList = new Array();
//	var linkStrArray = new Array();
	//优先处理云，有还原操作
	var nephogramStr = customNephogramPublic.toXml(scene).nephogramStr;
	for(var i=0;i<scene.childs.length;i++){
		var child = scene.childs[i];
		if(child instanceof CustomNode){
//			var tempstr = child.serialize();
			if(child.type == "appSystem")
			{
				var temp = '<appSystem><id>'+child.id+'</id><name>'+child.text+'</name><x>'+child.x+'</x><y>'+child.y+'</y></appSystem>';
				nodeStr2 += temp;
			}
			else
			{
				nodeStr += child.serialize();
				nodeSecDomainList.push(child.asset.securityDomainId);
			}
			//nodeStr += child.serialize();
			nodeNum++;
			//nodeSecDomainList.push(child.asset.securityDomainId);
		}else if(child instanceof CustomLink){
			if(child.isMylink){
				linkStr2 += nodeFunction.getLinkXmlFromLinkNode(child,"myline");
			}
			else
				linkStr += child.serialize();
		}else if(child instanceof CustomTextNode){
			linkStr += child.serialize();
		}else if(child instanceof CustomContainer){
			containerStr += child.serialize();
		}
	}
	nodeSecDomainList.filter(function (item){
		if(nodeSecDomainList.indexOf(item) != -1){
			return false;
		}else return true;
	});
	str += nodeStr;
	str += '</nodes>';
	
	str += '<mynodes>';
	str += nodeStr2;
	str += '</mynodes>';

	str += '<lines>';
	str += linkStr;
	str += '</lines>';
	
	str += '<mylines>';
	str += linkStr2;
	str += '</mylines>';

	str += '<nephograms>';
	str += nephogramStr;
	str += '</nephograms>';

	str += '<dynTexts>';
	str += textStr;
	str += nodeFunction.getTextNodeXml(scene,"dynText");
	str += '</dynTexts>';

	str += '<squareBoxes>';
	str += containerStr;
	str += group.toXml2(scene);
	str += '</squareBoxes>';

	str += '</root>';

//	var xml = json2xml.parseXmlString(str);
//	console.log(xml);
	var imageData = mainCanvas.toDataURL('image/png');
	var json = {
			topoId : topoId,
			topoXML : str,
			amount : nodeNum,
			defaultShow : this_params.defaultShow?this_params.defaultShow:0,
			secIdFilteredArr : nodeSecDomainList.join(),
			currTheme : this_params.themePath,
			DeltaInfoFlag : 0,
			regionId : this_params.regionId
			,
			imageData : imageData
		};
	$.ajax({
		url : index_web_app + index_soc_prefix + 'topoManage/addTopoDetailNew',
		data : json,
		type : 'post',
		dataType : 'json',
		async : true,
		timeout : 120000,
		xhrFields: {
			withCredentials: true
		},
		success : function (data){
			g_dialog.operateAlert(null,"保存成功！","info");
			init();
		},
		error : function (e){
			if (e.status == 200 && e.statusText == "OK")
			{
				//回调
				saveCallback(e.responseText);
			}
			g_dialog.waitingAlertHide();
			if(e.statusText == "timeout")
			{
				g_dialog.operateAlert(null,"响应超时!","error");
			}
			init();
		}
	});
}
function saveCallback(result){
	g_dialog.operateAlert(null,"保存成功！","info");
	//console.log(result)
	// console.log(json2xml2.parseXmlString(result));
	// var jsonObj = json2xml2.xml_str2json(result);
	// formatJson(jsonObj);
}

         });
});